package com.bidcms.web.model;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Hashtable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.bidcms.dao.attachmentMapper;
import com.bidcms.domain.attachment;
import com.bidcms.util.DrawImage;
import com.bidcms.util.FeatureClass;
import com.bidcms.util.UploadFileType;
import com.bidcms.web.BaseController;
import com.google.gson.JsonObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import common.utils.DateUtils;

@Controller
@RequestMapping("models/common")
public class common extends BaseController {

	@Autowired
	private attachmentMapper attachmentDao;

	// pagehelp/help
	@ResponseBody
	@RequestMapping(value = "pagehelp/help", method = RequestMethod.GET)
	public ModelAndView feature_list(HttpServletRequest req,
			HttpServletResponse resp) {
		ModelAndView mv = new ModelAndView("help");
		return mv;
	}

	@ResponseBody
	@RequestMapping(value = "ironDb/list", method = RequestMethod.GET)
	public String ironDb_list(HttpServletRequest req) {
		FileReader fr = null;
		BufferedReader br = null;
		StringBuilder sb = new StringBuilder();
		try {
			fr = new FileReader(getRealPath(req, "/data") + "/irobDb.json");
			br = new BufferedReader(fr);
			String s;
			while ((s = br.readLine()) != null) {
				sb.append(s);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	// qiniu//upToken.php
	@ResponseBody
	@RequestMapping(value = "qiniu/upToken", method = RequestMethod.POST)
	public String qiniu_upToken(HttpServletRequest req, HttpServletResponse resp) {
		// $uploadToken='52vlMlaPE9u_BKOXzfqGxMfDM5fRf1-uqz5W55KD';
		// echo '{"code":0,"msg":"ok","data":{"uptoken":"'.$uploadToken.'"}}';
		String uploadToken = "52vlMlaPE9u_BKOXzfqGxMfDM5fRf1-uqz5W55KD";
		JsonObject token = new JsonObject();
		token.addProperty("uptoken", uploadToken);
		JsonObject json = new JsonObject();
		json.addProperty("code", 0);
		json.addProperty("msg", "ok");
		json.add("data", token);
		return json.toString();
	}

	@ResponseBody
	@RequestMapping(value = "qiniu/download", method = RequestMethod.GET)
	public String qiniu_download(HttpServletRequest req,
			HttpServletResponse resp, String attachment_url) {
		HttpClient httpclient = new DefaultHttpClient();

		HttpGet httpget = new HttpGet(attachment_url);
		InputStream instream = null;
		long length = 0l;
		try {
			HttpResponse response = httpclient.execute(httpget);
			System.out.println(response.getStatusLine());
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				instream = entity.getContent();
				length = entity.getContentLength();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (RuntimeException ex) {
			httpget.abort();
			throw ex;
		} finally {
			try {
				instream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		httpclient.getConnectionManager().shutdown();
		return new Long(length).toString();
	}

	@ResponseBody
	@RequestMapping(value = "qiniu/upload", method = RequestMethod.POST)
	public String qiniu_upload(HttpServletRequest req,
			HttpServletResponse resp, MultipartFile file) {
		// 原始文件名
		String originalFilename = file.getOriginalFilename();
		String newFileName = System.nanoTime() + originalFilename;
		Integer fileSize = new Long(file.getSize()).intValue();
		// 2015/12
		String ym = DateUtils.getFormatCustomDateString(new Date(), "yyyy/MM");
		// data/upload/1/2015/12/11225d4724f654ae3d12c2be879dc942.gif
		JsonObject json = new JsonObject();
		JsonObject data = new JsonObject();
		String parent = getRealPath(req, "/data/upload") + "/" + ym + "/";
		File targetFile = new File(parent);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		targetFile = new File(parent + newFileName);
		String type = file.getContentType().substring(0,
				file.getContentType().lastIndexOf("/"));
		// 保存
		try {
			file.transferTo(targetFile);
			attachment atth = new attachment();
			int width = 0;
			int height = 0;
			switch (UploadFileType.getType(type)) {
			case audio:
				atth.setMediaType("");
				break;
			case image:
				DrawImage di = new DrawImage(targetFile, parent
						+ targetFile.getName() + "!100x100.jpg");
				di.resize(100, 100);
				width = di.getWidth();
				height = di.getHeight();
				atth.setMediaType("image");
				break;
			default:
				break;
			}
			String dataUrl = "data/upload/" + ym + "/" + newFileName;
			atth.setStoreId(1);
			atth.setTitle(originalFilename.length()>50?originalFilename.substring(0,50):originalFilename);
			atth.setUrl(dataUrl);
			atth.setThumbUrl(dataUrl);

			atth.setCreatedTime(Integer.valueOf(new Long(new Date().getTime())
					.toString().substring(0, 10)));
			atth.setSize(fileSize);
			atth.setWidth(width);
			atth.setHeight(height);
			atth.setGoodsId(0);
			attachmentDao.insert(atth);
			json.addProperty("code", 0);
			json.addProperty("msg", "ok");
			data.addProperty("attachment_file", originalFilename);
			data.addProperty("attachment_full_url", dataUrl);
			data.addProperty("attachment_id", atth.getId());
			data.addProperty("attachment_size", fileSize.toString());
			data.addProperty("attachment_title", "tpl_fbb_bg_1");
			data.addProperty("attachment_url", dataUrl);
			data.addProperty("created_time", new Date().getDate());
			data.addProperty("height", 0);
			data.addProperty("thumb_file", dataUrl);
			data.addProperty("thumb_url", "data/upload/" + ym + "/"
					+ newFileName);
			data.addProperty("width", 0);
			json.add("data", data);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json.toString();
	}

	@RequestMapping(value = "url/create", method = RequestMethod.GET)
	public void url_create(HttpServletRequest req, HttpServletResponse resp,
			String type, String id) {
		// QRcode::png(SITE_ROOT.'/index.php?con=show&bid_id='.intval($_GET['bid_id']),
		// "./code.png",'L',4,0,true); //����pngͼƬ
		// }
		// elseif($_GET['type']=='usercenter')
		// {
		// QRcode::png($picUrl=SITE_ROOT.'/index.php?con=buyer&act=usercenter',
		// "./code.png",'L',4,0,true); //����pngͼƬ
		// }
		// elseif($_GET['type']=='goods')
		// {
		// if(!empty($_GET['id']))
		// {
		// $picUrl=SITE_ROOT.'/index.php?con=show&act=goods&id='.$_GET['id'];
		// }
		// QRcode::png($picUrl, "./code.png",'L',4,0,true); //����pngͼƬ
		StringBuilder sb = new StringBuilder();
		// sb.append("localhost:8080/fesco-web");
		switch (FeatureClass.getClass(type)) {
		case homepage:
			sb.append("index?con=show&id=" + id);
			break;
		case usercenter:
			sb.append("/index?con=buyer&act=usercenter");
			break;
		case goods:
			sb.append("/index?con=show&act=goods&id=" + id);
			break;
		case non:
			sb.append("index?con=showcase&act=feature");
			break;
		default:
			break;
		}
		Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();

		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

		BitMatrix matrix = null;

		try {

			matrix = new MultiFormatWriter().encode(sb.toString(),
					BarcodeFormat.QR_CODE, 300, 300, hints);

		} catch (WriterException e) {

			e.printStackTrace();

		}
		resp.setContentType("image/jpg");
		try {
			OutputStream stream = resp.getOutputStream();
			MatrixToImageWriter.writeToStream(matrix, "jpg", stream);
		} catch (IOException e) {

			e.printStackTrace();

		}
	}

	public static void main(String[] args) {
		System.out.println("image/jpg".substring(0,
				"image/jpg".lastIndexOf("/")));
	}
}
